package controllerfront

import (
	"freely/bin/before"
	"freely/bin/comm"
	"freely/bin/crud"
	"freely/bin/utils"
	"freely/src/constant"
	"freely/src/methods"
	modelfront "freely/src/model/front"
	sourcefront "freely/src/source/front"
	"net/http"

	"github.com/gin-gonic/gin"
)

type ControllerFrontUsers struct {
	*crud.Controller
}

var frontUsersClass *sourcefront.SourceFrontUsers

func init() {
	frontUsersClass = sourcefront.NewSourceFrontUsers()
}

/**
 * 当前用户
 */
func (c *ControllerFrontUsers) Person(ctx *gin.Context) {
	userId := ctx.GetUint(constant.AuthUserID)

	user, err := frontUsersClass.SourceInfo(userId)
	if err != nil {
		ctx.JSON(http.StatusOK, before.ReqFail(ctx, err.Error()))
		return
	}

	ctx.JSON(http.StatusOK, before.ReqOk(ctx, user))
}

/**
 * 退出登录
 */
func (c *ControllerFrontUsers) Logout(ctx *gin.Context) {
	userId := ctx.GetUint(constant.AuthUserID)
	auth := ctx.GetHeader(constant.Author)
	tokenHash := utils.StrToHash(auth)
	// 删除redis中保存的用户信息
	comm.RedisCli.SRem(comm.AppCtx, constant.RedisOnlineUsers, userId)
	comm.RedisCli.Del(comm.AppCtx, tokenHash)

	ctx.JSON(http.StatusOK, before.ReqOk(ctx, "退出成功"))
}

/**
 * 刷新token
 */
func (c *ControllerFrontUsers) RefreshToken(ctx *gin.Context) {
	userId := ctx.GetUint(constant.AuthUserID)
	username := ctx.GetString(constant.AuthUsername)
	roleId := ctx.GetUint(constant.AuthRoleID)
	roleName := ctx.GetString(constant.AuthRole)
	loginAt := ctx.GetString(constant.AuthFromTo)

	jwt := &methods.JwtData{
		UserID:   userId,
		Username: username,
		RoleID:   roleId,
		Role:     roleName,
		LoginAt:  loginAt,
	}

	token, err := loginClass.RefreshToken(jwt, expireTime)
	if err != nil {
		ctx.JSON(http.StatusOK, before.ReqFail(ctx, err.Error()))
		return
	}

	ctx.JSON(http.StatusOK, before.ReqOk(ctx, token))
}

func RegisterControllerFrontUsers(group *gin.RouterGroup) {
	var apis = []string{"/add", "/update", "/delete", "/list", "/page", "/info"}

	var controller = &ControllerFrontUsers{
		&crud.Controller{
			Module: modelfront.ModelName,
			Source: frontUsersClass,
		},
	}

	var extendApi = map[string]*crud.RouterItem{
		"/person":       {From: crud.RouterGet, Call: controller.Person},
		"/logout":       {From: crud.RouterGet, Call: controller.Logout},
		"/refreshToken": {From: crud.RouterPost, Call: controller.RefreshToken},
	}

	crud.RegisterController(group, controller, apis, extendApi)
}
